package com.lmabbe.common.global.result;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author lmabbe
 * @data 2021/2/7 22:47
 */
@Slf4j
@Builder
@Accessors(chain = true)
@Data
@ApiModel(value = "返回实体类")
public class R<T> {

    @ApiModelProperty(value = "返回代码")
    private Integer code;

    @ApiModelProperty(value = "提示信息")
    private String message;

    @ApiModelProperty(value = "数据")
    private T data;

    @ApiModelProperty(value = "扩展数据")
    private Map<String, Object> extra;

    @ApiModelProperty(value = "时间戳")
    private Long timestamp;

    public static R success() {
        return new RBuilder<>().code(200).message("操作成功!").timestamp(System.currentTimeMillis()).build();
    }

    public static <T> R success(T obj) {
        return new RBuilder<>().code(200).message("操作成功!").data(obj).timestamp(System.currentTimeMillis()).build();
    }

    public static <T> R page(IPage<T> page) {
        return new RBuilder<>().code(200).message("操作成功!").data(page.getRecords()).extra(Map.of("total", page.getTotal())).timestamp(System.currentTimeMillis()).build();
    }

    public static R fail() {
        return fail("fail");
    }

    public static R fail(String message) {
        return new RBuilder<>().code(405).message(message).timestamp(System.currentTimeMillis()).build();
    }


    public static R error() {
        return error(null);
    }

    public static R error(Integer code, String message) {
        return new RBuilder<>()
                .code(code)
                .message(StrUtil.isBlank(message) ? "error" : message)
                .build();
    }


    public static R error(String message) {
        return error(500, message);
    }
}
